/*
 * @Date: 2022-11-13 11:38:17
 * @LastEditors: sailornpg
 * @LastEditTime: 2022-11-29 14:36:55
 * @FilePath: \vue-admin-ts\src\utils\mapMenus\index.ts
 * @Description: mapMenus ./views/**.vue
 */
import type { RouteRecordRaw } from "vue-router";
type TMapMeueToRoutes = (userMenus: any[]) => RouteRecordRaw[];
let firstMenu: any = null;
export const mapMenuToRoutes: TMapMeueToRoutes = (userMenus) => {
  const routes: RouteRecordRaw[] = [];
  //所有默认routes
  const allRoutes: RouteRecordRaw[] = [];
  const routeFiles = import.meta.glob("../../router/main/**/*.ts", {
    eager: true,
  });
  Object.keys(routeFiles).forEach((key) => {
    const route: any = routeFiles[key];
    allRoutes.push(route.default);
  });
  //处理传入的userMenus
  const stack = [...userMenus];
  while (stack.length) {
    const cur = stack.shift();
    if (cur.type === 2) {
      const route = allRoutes.find((item) => cur.url === item.path);
      if (route) {
        routes.push(route);
      }
      if (!firstMenu) {
        firstMenu = cur;
      }
    } else {
      if (cur.children) {
        stack.push(...cur.children);
      }
    }
  }
  return routes;
};

export const pathMapToMenu = (userMenus: any[], curPath: string) => {
  const stack = [...userMenus];
  while (stack.length) {
    const cur = stack.pop();
    if (cur.type === 2 && cur.url === curPath) {
      return cur;
    } else {
      if (cur.children) {
        stack.push(...cur.children);
      }
    }
  }
};
export const mapMenusToPermissions = (userMenus: any[]) => {
  const permissions: string[] = [];
  const stack = [...userMenus];
  while (stack.length) {
    const cur = stack.pop();
    if (cur.type === 3) {
      permissions.push(cur.permission);
    } else {
      if (cur.children) {
        stack.push(...cur.children);
      }
    }
  }
  return permissions;
};
export { firstMenu };
